const $sql = require('../sqlfun');//sql语句
var models = require('../connectmysql');//数据库链接信息
var mysql = require('mysql');
const qiniu=require('qiniu');
var conn = mysql.createConnection(models.mysql);
conn.connect();

module.exports = (req, res) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  //res.setHeader("Access-Control-Allow-Methods", "POST");
  console.log("上传中");
  //检测文件夹是否存在
  var sql = $sql.datames.selectimage;
  let params = req.body;
  console.log("params",params);
  conn.query(sql,[params.sfname], function(err, data) {
    if(err){
      console.log(err);
      res.send(err);
    }
    else {
      var result={
        "status":"200",
        "message":"success",
        data:data
      }
      console.log(result.data[0].newname);
      //----------------下面开始上传----------------------
      const bucket = 'temporary';  //七牛云存储空间名字
      const qiniuUrl = 'pavm4yutx.bkt.clouddn.com';//七牛云的域名
      let token, putPolicy;  //设置token扫描器,putPolicy上传策略
      let filepath;  //文件上传后的路径
      let key = result.data[0].newname;  //上到七牛云后文件的名字
      //七牛云个人密钥
      let AK = 'Voa-weDtnRpPIqbyO37ucaNLTGsU_7tA8dladuV-';
      let SK = 'moQVxM1EQU-ruWSzeI8R_KcGOxsj9O7Ev0v95qbs';
      //定义鉴定对象mac
      var mac = new qiniu.auth.digest.Mac(AK, SK);

      filepath = qiniuUrl + '/' + key;//文件上传后的地址赋值
      console.log("文件上传后的地址", filepath);

      //上传凭证
      var option = {
        scope: bucket,
        expire: 7200, //上传凭证有效时间
        returnBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","fname":$(fname),"mimeType":$(mimeType),"ext":$(ext)}', //回调内容，具体看七牛云官方文档
      }
      putPolicy = new qiniu.rs.PutPolicy(option);
      token = putPolicy.uploadToken(mac);
      console.log(token);
      //构建配置对象
      var config = new qiniu.conf.Config();
      config.zone = qiniu.zone.Zone_z2;//华南服务器
      //文件上传
      var localFile = result.data[0].imagepath;//本地缓存的文件路径
      var formUploader = new qiniu.form_up.FormUploader(config);
      var putExtra = new qiniu.form_up.PutExtra();

      formUploader.putFile(token, key, localFile, putExtra, function (respErr, respBody, respInfo) {
        if (respErr) {
          throw respErr;
        }
        if (respInfo.statusCode == 200) {
          console.log('上传成功',respBody);
          var sql2=$sql.datames.uploadimg;
          console.log(sql2);
          conn.query(sql2,[filepath,params.sfname], function(err, data) {
            if(err){
              console.log(err);
              //res.send(err);
            }
            else {
              var result = {
                "status": "200",
                "message": "success",
              }
              console.log('上传路径'+filepath);
              //res.send(result);
              var sql3=$sql.datames.selectfoodbbs;
              console.log(sql3);
              conn.query(sql3, function(err, data) {
                console.log(data.length);
                var le=data.length+1;
                var sql4=$sql.datames.addarticle;
                console.log(sql4);
                conn.query(sql4,[params.stopic,params.sctx,params.suser,'0',le,params.stime,filepath], function(err, data) {
                  if(err){
                    console.log(err);
                    res.send(err);
                  }
                  else {
                    var result = {
                      "status": "200",
                      "message": "add article success",
                      data:data
                    }
                    console.log("文件增加成功"+result);
                    res.send(result);
                  }
                })
              });
            }
          });
        } else {
          console.log(respInfo.statusCode);
          console.log(respBody);
        }
      });
    }
  })
}
